#include "shell_port.h"

Shell 	shell;
char 	shellBuffer[512];
uint8_t shell_code_receive_buffer[SHELL_RECEIVE_LENGTH_MAX];
uint8_t shell_code_receive_flag;
int     shell_code_receive_count;


/*
 * @brief SHELL指令接收串口初始化
 */
void SHELL_receive_init(void)
{
	__HAL_UART_ENABLE_IT(&SHELL_UART_HANDLE,UART_IT_IDLE);
	HAL_UART_Receive_DMA(&SHELL_UART_HANDLE, shell_code_receive_buffer, SHELL_RECEIVE_LENGTH_MAX);
	SCB_CleanInvalidateDCache();//H7开启DCache后启用此行
}

/*
 * @brief SHELL指令接收中断处理
 */
void SHELL_Code_Receive_IQR_Handler(void)
{
	if(__HAL_UART_GET_FLAG(&SHELL_UART_HANDLE,UART_FLAG_IDLE)!=RESET)
	{
		HAL_UART_DMAStop(&SHELL_UART_HANDLE);
		__HAL_UART_CLEAR_IDLEFLAG(&SHELL_UART_HANDLE);
		shell_code_receive_count=SHELL_RECEIVE_LENGTH_MAX-__HAL_DMA_GET_COUNTER(&SHELL_DMA_RX);
		shell_code_receive_flag=1;
	}

}






/**
 * @brief 用户shell写
 * 
 * @param data 数据
 * @param len 数据长度
 * 
 * @return short 实际写入的数据长度
 */
short userShellWrite(char *data, unsigned short len)
{
    HAL_UART_Transmit(&SHELL_UART_HANDLE, (uint8_t *)data, len, 0xFF);
    return len;
}


/**
 * @brief 用户shell读
 * 
 * @param data 数据
 * @param len 数据长度
 * 
 * @return short 实际读取到
 */
short userShellRead(char *data, unsigned short len)
{
	static uint8_t count=0;
	if(shell_code_receive_flag==1)
	{
		*data=shell_code_receive_buffer[count];
		count++;
		if(count>=shell_code_receive_count)
		{
			count=0;
			shell_code_receive_flag=0;
			HAL_UART_Receive_DMA(&SHELL_UART_HANDLE, shell_code_receive_buffer, SHELL_RECEIVE_LENGTH_MAX);
			SCB_CleanInvalidateDCache();//H7开启DCache后启用此行
		}
		return 1;
	}
	else
	{
		osDelay(10);
		return -1;
	}
}

/**
 * @brief 用户shell上锁
 * 
 * @param shell shell
 * 
 * @return int 0
 */
int userShellLock(Shell *shell)
{
    osMutexWait(ShellMutexHandle, portMAX_DELAY);
    return 0;
}

/**
 * @brief 用户shell解锁
 * 
 * @param shell shell
 * 
 * @return int 0
 */
int userShellUnlock(Shell *shell)
{
    osMutexRelease(ShellMutexHandle);
    return 0;
}


















/**
 * @brief 用户shell初始化
 * 
 */
void userShellInit(void)
{


    shell.write = userShellWrite;
    shell.read = userShellRead;
    shell.lock = userShellLock;
    shell.unlock = userShellUnlock;
    SHELL_receive_init();
    shellInit(&shell, shellBuffer, 512);

}






int __io_putchar(int ch)
{
	HAL_UART_Transmit(&STANDARD_UART_IO_HANDLE, (uint8_t *)&ch, 1, 100);
	return 0;
}



#define SHELL_TX_BUFFER_SIZE 256
char SHELLTxBuffer[SHELL_TX_BUFFER_SIZE];
void shellendprintf(const char *format,...)
{
	va_list args;
	uint32_t length;

	va_start(args,format);
	length=vsnprintf((char *)SHELLTxBuffer,256,(char *)format,args);
	va_end(args);
	shellWriteEndLine(&shell, SHELLTxBuffer, length);
//	HAL_UART_Transmit(&SHELL_UART_HANDLE, (uint8_t *)SHELLTxBuffer, length, 100);
}














































